import { observable, action } from 'mobx-miniprogram';
import { standardizeGlobalStore } from '../helpers/store_standardizer.js';

// 主题相关常量
const THEME_KEY = 'UI_THEME';
const FONT_SIZE_KEY = 'UI_FONT_SIZE';

// 创建UI状态管理Store
export const uiStore = observable({
  // 主题设置
  theme: 'light', // light, dark
  
  // 字体大小
  fontSize: 'normal', // small, normal, large
  
  // 页面加载状态
  isLoad: false,
  
  // 全局加载状态
  loading: {
    global: false,
    tasks: {}
  },
  
  // 全局错误
  errors: {
    global: null,
    modules: {}
  },
  
  // Toast消息
  toast: {
    show: false,
    type: 'info', // info, success, error, warning
    message: '',
    duration: 2000
  },
  
  // 初始化
  init: action(function() {
    // 重置页面加载状态
    this.isLoad = false;
    
    // 从缓存恢复UI设置
    try {
      const theme = wx.getStorageSync(THEME_KEY);
      if (theme) this.theme = theme;
      
      const fontSize = wx.getStorageSync(FONT_SIZE_KEY);
      if (fontSize) this.fontSize = fontSize;
    } catch (e) {
      console.error('获取UI设置失败:', e);
    }
  }),
  
  // 设置页面加载状态
  setIsLoad: action(function(status) {
    this.isLoad = !!status;
  }),
  
  // 设置主题
  setTheme: action(function(theme) {
    this.theme = theme;
    try {
      wx.setStorageSync(THEME_KEY, theme);
    } catch (e) {
      console.error('保存主题设置失败:', e);
    }
  }),
  
  // 设置字体大小
  setFontSize: action(function(size) {
    this.fontSize = size;
    try {
      wx.setStorageSync(FONT_SIZE_KEY, size);
    } catch (e) {
      console.error('保存字体大小设置失败:', e);
    }
  }),
  
  // 设置加载状态
  setLoading: action(function(key, status) {
    if (!key) {
      this.loading.global = status;
    } else {
      this.loading.tasks[key] = status;
    }
  }),
  
  // 批量设置加载状态
  setBatchLoading: action(function(keyStatusMap) {
    if (!keyStatusMap || typeof keyStatusMap !== 'object') return;
    
    Object.entries(keyStatusMap).forEach(([key, status]) => {
      if (key === 'global') {
        this.loading.global = status;
      } else {
        this.loading.tasks[key] = status;
      }
    });
  }),
  
  // 清除所有加载状态
  clearAllLoading: action(function() {
    this.loading.global = false;
    this.loading.tasks = {};
  }),
  
  // 清除特定模块的加载状态
  clearModuleLoading: action(function(modulePrefix) {
    if (!modulePrefix) return;
    
    Object.keys(this.loading.tasks).forEach(key => {
      if (key.startsWith(modulePrefix)) {
        delete this.loading.tasks[key];
      }
    });
  }),
  
  // 执行异步操作并自动处理加载状态
  withLoading: action(async function(key, asyncFunction) {
    if (!asyncFunction || typeof asyncFunction !== 'function') return null;
    
    this.setLoading(key, true);
    try {
      const result = await asyncFunction();
      return result;
    } finally {
      this.setLoading(key, false);
    }
  }),
  
  // 计算属性：是否有活跃的加载
  get isLoading() {
    if (this.loading.global) return true;
    return Object.values(this.loading.tasks).some(status => status === true);
  },
  
  // 计算属性：特定模块是否在加载
  isModuleLoading(modulePrefix) {
    if (this.loading.global) return true;
    return Object.keys(this.loading.tasks).some(
      key => key.startsWith(modulePrefix) && this.loading.tasks[key] === true
    );
  },
  
  // 设置错误
  setError: action(function(module, error) {
    if (!module) {
      this.errors.global = error;
    } else {
      this.errors.modules[module] = error;
    }
  }),
  
  // 清除错误
  clearError: action(function(module) {
    if (!module) {
      this.errors.global = null;
    } else {
      this.errors.modules[module] = null;
    }
  }),
  
  // 清除所有错误
  clearAllErrors: action(function() {
    this.errors.global = null;
    this.errors.modules = {};
  }),
  
  // 清除特定模块的所有错误
  clearModuleErrors: action(function(modulePrefix) {
    if (!modulePrefix) return;
    
    Object.keys(this.errors.modules).forEach(key => {
      if (key.startsWith(modulePrefix)) {
        delete this.errors.modules[key];
      }
    });
  }),
  
  // 显示Toast
  showToast: action(function(options) {
    this.toast = {
      show: true,
      type: options.type || 'info',
      message: options.message || '',
      duration: options.duration || 2000
    };
    
    // 自动隐藏
    setTimeout(() => {
      this.hideToast();
    }, this.toast.duration);
  }),
  
  // 隐藏Toast
  hideToast: action(function() {
    this.toast.show = false;
  }),
  
  // 显示成功提示
  showSuccess: action(function(message, duration = 2000) {
    this.showToast({
      type: 'success',
      message,
      duration
    });
  }),
  
  // 显示错误提示
  showError: action(function(message, duration = 2000) {
    this.showToast({
      type: 'error',
      message,
      duration
    });
  }),
  
  // 显示警告提示
  showWarning: action(function(message, duration = 2000) {
    this.showToast({
      type: 'warning',
      message,
      duration
    });
  }),
  
  // 显示信息提示
  showInfo: action(function(message, duration = 2000) {
    this.showToast({
      type: 'info',
      message,
      duration
    });
  })
});

// 应用标准化Store，确保拥有所有必要的方法和错误处理
export default standardizeGlobalStore(uiStore, 'ui'); 